#include "delegate.h"
#include <QApplication>
#include <QtGui>

Delegate::Delegate(DownloadTableModel *model):
    QSqlRelationalDelegate(model), model(model){}

void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    int progress, min, column = index.column();
    QRect rect;
    switch (column){
    case 4:
        static QStyleOptionProgressBarV2 progressBarOption;
        progressBarOption.state = QStyle::State_Enabled;
        progressBarOption.direction = QApplication::layoutDirection();
        progressBarOption.rect = option.rect;

#if defined(Q_OS_MACX) //strange behavior: no vertical justify, height is fixed as probably text height.
        progressBarOption.rect.setTop(option.rect.top() + (option.rect.height() - option.fontMetrics.lineSpacing()) / 2);
#endif
        progressBarOption.fontMetrics = QApplication::fontMetrics();
        progressBarOption.minimum = 0;
        progressBarOption.maximum = 1000;
        progressBarOption.textAlignment = Qt::AlignCenter;
        progressBarOption.textVisible = true;

        progress = model->data(index).toInt();
        progressBarOption.progress = progress < 0 ? 0 : progress;
        progressBarOption.text = QString().sprintf("%lf%%", (progressBarOption.progress / 10.0));

        QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);
        break;
    case 3:
        static QImage low(":icons/low.png");
        static QImage mid(":icons/mid.png");
        static QImage high(":icons/high.png");

        QImage * icon;
        switch(model->data(index).toInt()){
        case 0: icon = &low; break;
        case 2: icon = &high; break;
        default:icon = &mid;
        }
        rect = option.rect;
        min = (rect.height() > rect.width() ? rect.width() : rect.height());
        rect.setLeft(rect.left() + (rect.width() - min) / 2);
        rect.setTop(rect.top() + (rect.height() - min) / 2);
        rect.setWidth(min);
        rect.setHeight(min);
        painter->drawImage(rect,*icon);
        break;
    default:
        QSqlRelationalDelegate::paint(painter, option, index);
    }
}

QWidget *Delegate::createEditor(QWidget *parent,
                                const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
    return NULL;
}
